import { winston,createLogger, format, transports } from "winston";
import expressWinston from "express-winston";
import path from 'path';
import winstonDailyRotatFile from 'winston-daily-rotate-file'

const { combine, timestamp, label, printf } = format;


// 请求日志记录，包括相应时间，接口名，返回值
const DailyRotateFileTransport = (fileName) => {
    return new (winstonDailyRotatFile)({
        filename: path.join(process.env.LOGPATH || './logs', `${fileName} %DATE%.log`),
        datePattern: 'YYYY-MM-DD HH',
        maxSize: '20m',
        maxFiles: '7d',
        timeStamp: () =>  new Date()
    })
}
const errLog = expressWinston.errorLogger({
    transports: [
        // 控制台
        // new winston.transports.Console({
        //   json: true,
        //   colorize: true
        // }),
        new winston.transports.File({
          filename: 'logs/werrs.log'
        })
    ],
    meta: true,
    msg: "HTTP {{req.method}} {{req.url}}",
    expressFormat: true,
    level: function (req, res) {
        var level = "";
        if (res.statusCode >= 100) { level = "info"; }
        if (res.statusCode >= 400) { level = "warn"; }
        if (res.statusCode >= 500) { level = "error"; }
        // Ops is worried about hacking attempts so make Unauthorized and Forbidden critical
        if (res.statusCode == 401 || res.statusCode == 403) { level = "critical"; }
        // No one should be using the old path, so always warn for those
        if (req.path === "/v1" && level === "info") { level = "warn"; }
        return level
    }
});

const apiLog = (req, res, next) => {
    // 接口请求详细信息，相应时间，返回参数 等
    let send = res.send
    let content = ''
    let query = req.query || {}
    let body = req.body || {}
    res.send = function () {
        content = arguments[0]
        send.apply(res, arguments)
    }
    expressWinston.logger({
        transports: [
            DailyRotateFileTransport('api-log')
        ],
        formatter: function(options) {
            // Return string will be passed to logger.
            return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') +
                (options.meta && Object.keys(options.meta).length ? '\n\t'+ JSON.stringify(options.meta) : '' );
        },
        // meta: true, // optional: control whether you want to log the meta data about the request (default to true)
        msg () {
            return `HTTP ${req.method} ${req.url} query ${JSON.stringify(query)} body ${JSON.stringify(body)} resData ${content} `
        },
        colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
        ignoreRoute: function (req, res) {
            if (req.headers.self) return true
            return false
        } // optional: allows to skip some log messages based on request and/or response
    })(req, res, next)
}

// const appLog = expressWinston.logger({
//     transports: [
//         // DailyRotateFileTransport('app-log')
//     ],
//     meta: false, // optional: control whether you want to log the meta data about the request (default to true)
//     msg: 'HTTP {{req.method}} {{req.url}}', // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
//     expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
//     colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
//     ignoreRoute: function (req, res) {
//         // 只打印页面请求信息
//         let notPageRequest = false
//         let ignoreArr = ['/api', '.js', '.css', '.png', '.jpg', '.gif']
//         ignoreArr.forEach(item => {
//             if (req.url.indexOf(item) > -1) notPageRequest = true
//         })
//         return notPageRequest
//     } // optional: allows to skip some log messages based on request and/or response
//
// })


export {errLog,apiLog}